<?php
require_once dirname(__FILE__).'/../../../config.php';
require_once cf\Config::path.'/api/admin.php';

$ymlID = (int)$argv[1];

function getManufacturerID($name) {
	static $qNew = null;
	cf\createStaticQuery($qNew,"INSERT INTO cf_manufacturers (name) VALUES (:name)");
	static $manufacturers = null;
	if (!$manufacturers) {
		$manufacturers = cf\query2arrays("SELECT name,id FROM cf_manufacturers",array(),false,'name');
	}
	
	if (array_key_exists($name,$manufacturers)){
		return $manufacturers[$name]['id'];
	}

	$qNew->setParam('name',$name)->execute();
	global $db;
	$id = $db->lastInsertId();
	$manufacturers[$name] = array('id'=>$id);
	return $id;
}

function addProduct($offer, $categories) {
	global $ymlID, $catMatch, $sellerID, $newState;
	
	if (!count(array_intersect($categories,array_keys($catMatch)))) {
		return false;
	}
	
	static $qFind = null;
	if (!$qFind) {
		cf\createStaticQuery($qFind,"SELECT id FROM cf_products WHERE seller_id=:seller_id AND link=:link",array('seller_id'=>$sellerID));
	}
	$found = $qFind->setParam('link',$offer['link'])->execute()->fetch();
	if ($found) {
		static $qUpdatePrice = null;
		if (!$qUpdatePrice) {
			cf\createStaticQuery($qUpdatePrice,"UPDATE cf_products SET price=:price WHERE id=:id");
		}
		$qUpdatePrice->setParam('price',$offer['price'])->setParam('id',$found['id'])->execute();
		
		global $updatedCount;
		++$updatedCount;
		return $found['id'];

	} else {
		$product =  array_merge(
			array(
				'code' => null,
		    	'manufacturer_id' => null,
				'name' => null,
				'model' => null,
				'short_descr' => null,
				'full_descr' => null,
				'price' => null,
				'discount' => null,
				'state_id' => $newState ? $newState : 1,
				'enabled_from' => null, 
				'enabled_to' => null, 
				'tags' => null,
				'article' => null,
				'tag_title' => null,
				'tag_meta_keywords' => null,
				'tag_meta_descr' => null,
				'image1'=>null,  'image1_text'=>null,  'image2'=>null,  'image2_text'=>null,  'image3'=>null,  'image3_text'=>null,  'image4'=>null,  'image4_text'=>null,  'image5'=>null,  'image5_text'=>null,
				'image6'=>null,  'image6_text'=>null,  'image7'=>null,  'image7_text'=>null,  'image8'=>null,  'image8_text'=>null,  'image9'=>null,  'image9_text'=>null,  'image10'=>null, 'image10_text'=>null, 
				'image11'=>null, 'image11_text'=>null, 'image12'=>null, 'image12_text'=>null, 'image13'=>null, 'image13_text'=>null, 'image14'=>null, 'image14_text'=>null, 'image15'=>null, 'image15_text'=>null,
				'image16'=>null, 'image16_text'=>null, 'image17'=>null, 'image17_text'=>null, 'image18'=>null, 'image18_text'=>null, 'image19'=>null, 'image19_text'=>null, 'image20'=>null, 'image20_text'=>null,
				'seller_id' => $sellerID,
				'link' => null
			), 
			$offer
		);
		
		$pid = cf\api\admin\doAction('product_add',$product);
		
		foreach ($categories as $fromCat) {
			if (array_key_exists($fromCat,$catMatch)) {
				cf\api\admin\doAction(
					'product_in_group_add',
					array('group_id'=>$catMatch[$fromCat]['to_id'], 'product_id'=>$pid, 'sort_order'=>500)
				);
			}
		}		

		global $addedCount;
		++$addedCount;
		
		return $pid;
	}
}

$stop = false;
$offersCount = 0;
$addedCount = 0;
$updatedCount = 0;
$deletedCount = 0;
$foundIDs = array();

try {
	$settings = cf\query2array("SELECT * FROM cf_import_yml WHERE id=:id",array('id'=>$ymlID));
	$sellerID = $settings['seller'];
	$newState = $settings['new_state'];
	$_SERVER['DOCUMENT_ROOT'] = getcwd()."/../../../..";
	
	$delFile = false;
	if ($argc>2) {      //second argument is a TMP file path to load data from
		$settings['url'] = $argv[2];
		$delFile = true;
	}

	$fieldsMatch = array(
		'NAME' => array(),
		'MODEL' => array(),
		'TYPEPREFIX' => array(),
		'DESCRIPTION' => array(),
		'URL' => array('link'),
		'PRICE' => array('price'),
		'VENDOR' => array('manufacturer_id'),
		'VENDORCODE' => array('article')
	);
	$fieldsMatch[strtoupper($settings['name_from'])][] = 'name';
	if ($settings['model_from']) {
		$fieldsMatch[strtoupper($settings['model_from'])][] = 'model';
	}
	if ($settings['short_descr_from']) {
		$fieldsMatch[strtoupper($settings['short_descr_from'])][] = 'short_descr';
	}
	if ($settings['full_descr_from']) {
		$fieldsMatch[strtoupper($settings['full_descr_from'])][] = 'full_descr';
	}
	
	$catMatch = cf\query2arrays("SELECT from_id,to_id FROM cf_import_yml_categories WHERE yml_id=:id",array('id'=>$ymlID),false,'from_id');

	$pictMatch = array();
	for ($i=1; $i<=10; ++$i){
		$pictMatch[$i] = $settings["image{$i}_from"] ? $settings["image{$i}_from"] : 0;
	}

	cf\execQuery("UPDATE cf_import_yml SET last_run=NOW(),last_state=0,offersCount=NULL,addedCount=NULL,updatedCount=NULL,deletedCount=NULL WHERE id=:id", array('id'=>$ymlID));
	
	$offer = array();
	$offerCategories = array();
	$pictNum = 0;
	$attr = false;
	$attrVal = '';
	function onStartTag($parser, $name, $attrs) {
		global $offer, $attr, $attrVal, $fieldsMatch, $offerCategories, $pictMatch, $pictNum;
		if ($name=='OFFER') {
			$offer = array();
			$offerCategories = array();
		}
		if ($name=='CATEGORYID') {
			$attr = 'cat';
		}
		if ($name=='PICTURE') {
			if ($pictMatch[++$pictNum]) {
				$attr = "image".$pictMatch[$pictNum];
			}
		}
		if (array_key_exists($name,$fieldsMatch)) {
			$attr = $fieldsMatch[$name];
		}
	}
	function onText($parser, $data) {
		global $attr, $attrVal;
		if ($attr) {
			$attrVal .= $data;
		}
	}
	function onEndTag($parser,$name) {
		global $attr, $attrVal, $offer, $offersCount, $offerCategories, $pictNum, $foundIDs, $stop;
		if ($attr) {
			if (is_string($attr) && $attr=='cat'){
				$offerCategories[] = $attrVal;
			} else if (is_string($attr) && substr($attr,0,5)=='image'){
				$_FILES[$attr] = array('type'=>'url', 'name'=>$attrVal);
			} else {
				if ($attr[0] == 'manufacturer_id') {
					$attrVal = getManufacturerID($attrVal);
				}
				foreach ($attr as $field) {
					$offer[$field] = $attrVal;
				}
			}
			$attr = false;
			$attrVal = '';
		}
		if ($name=='OFFER') {
			$pictNum = 0;
			++$offersCount;
			$id = addProduct($offer,$offerCategories);
			if ($id) {
				$foundIDs[$id] = true;
			}
			if ($offersCount > 4) {
				$stop = true;
			}
		}
	}

	$parser = xml_parser_create('UTF-8');
	xml_set_element_handler($parser, 'onStartTag', 'onEndTag');
	xml_set_character_data_handler ($parser, 'onText');
	
	$f = fopen($settings['url'],'r');
	if ($f===false) {
		throw new Exception("Could't open file:"+$settings['url']);
	}		
	while (($data=fread($f, 1024)) && !$stop) {
		if (!xml_parse($parser, $data, feof($f))) {
			throw new Exception(sprintf("XML error: %s at line %d",
				xml_error_string(xml_get_error_code($parser)),
				xml_get_current_line_number($parser))
			);
		}
	}
	xml_parser_free($parser);
	fclose($f);
	
	if ($sellerID) {
		$qDelete = cf\createQuery("UPDATE cf_products SET price=0 WHERE id=:id"); //or "DELETE FROM cf_products WHERE id=:id"
		$qDelState = cf\createQuery("UPDATE cf_products SET state=:state WHERE id=:id");
		$delState = $settings['del_state'];
		$qFindAllOfSeller = cf\createQuery("SELECT id FROM cf_products WHERE seller_id=:seller_id",array('seller_id'=>$sellerID));
		$qFindAllOfSeller->execute();
		while ($qFindAllOfSeller->fetch()) {
			$id = $qFindAllOfSeller->at('id');
			if (!array_key_exists($id,$foundIDs)) {
				$qDelete->setParam('id',$id)->execute();
				if ($delState) {
					$qDelState->setParam('state',$delState)->execute();
				}
				++$deletedCount;
			}
		}
	}

	if ($delFile) {
		unlink($settings['url']);
	}

	cf\execQuery("
		UPDATE cf_import_yml 
		SET 
			last_state=1,
			last_error=NULL,
			offersCount=$offersCount,
			addedCount=$addedCount,
			updatedCount=$updatedCount,
			deletedCount=$deletedCount 
		WHERE id=$ymlID
	");
	
} catch(Exception $e){
	cf\execQuery("
		UPDATE cf_import_yml 
		SET 
			last_state=2,
			last_error=:error,
			offersCount=$offersCount,
			addedCount=$addedCount,
			updatedCount=$updatedCount,
			deletedCount=$deletedCount 
		WHERE id=$ymlID",
		array('error'=>$e->getMessage())
	);
	return 1;
}

return 0;

?>